import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getJsonCookie, getStorage } from '@/utils/index.js'
// create an axios instance
const service = axios.create({
  // baseURL: process.env.BASE_API, // url = base url + request url VUE_APP_BASE_API

  // baseURL: process.env.VUE_APP_BASE_API, // 本地开发用
  // baseURL: '/test', // 本地开发用
  baseURL: '/api', //打包用
  // baseURL: 'http://22.54.93.85:8800/tdyp-sys', // 长源打包用
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 60, // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    console.log('config1', config)

    config.data = { name1: '1', name2: '2' }

    // do something before request is sent
    // const { token } = getJsonCookie('sToken')
    // const { userInfo } = getStorage('user_info')
    const { token } = store.state.login.userInfo.token
    console.log('token', store.state.login.userInfo.token)
    const userInfo = { userInfo: '123' }
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
      //所有请求体加上userId
      // if (userInfo && userInfo.userId && config.data) {
      // config.data.userId = userInfo.userId
      // config.data.orgId = userInfo.orgId
      // config.data = { name1: '1', name2: '2' }

      // }
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data

    // if the custom code is not 200, it is judged as an error.
    if (res.code && res.code !== 200) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000,
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)

export default service
